package com.jm.dao;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.persistence.Query;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.jm.entity.Agenttype;
import com.jm.entity.Area;
import com.jm.entity.User;
import com.jm.entity.Useraddress;

public class UserDao {

	
	public enum LEVEL_PRICE {
		ZONG_DAI,AGENT_LEVEL_1,AGENT_LEVEL_2,TEYUE_DAI,PINGPAI_DAI
	}
	/***
	 * 新增用户，用户申请后向用户表中插入一条记录
	 * @param level
	 * @param name
	 * @param phone
	 * @param idnumber
	 * @param wechat
	 * @param identifyicon
	 * @param authorizedpersonid
	 * @param lifepic
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public int addUser(String level,String name, String phone, String idnumber, String wechat, String identifyicon, long authorizedpersonid,
			String lifepic,int areaid) throws NoSuchAlgorithmException, UnsupportedEncodingException{

		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();//(SessionFactory) new Configuration().configure().buildSessionFactory();
		Session mSession = mSessionFactory.openSession();
		  Transaction tx = mSession.beginTransaction();
		try {
			  //查询是否已经注册
			   String hql = "from com.jm.entity.User u where u.account=:account or idnumber=:idnum";
			   //查询区域人数
			   String hql1 = "from com.jm.entity.Area a where a.areaid=:areid";
			   @SuppressWarnings("unchecked")
			   List<User>users = mSession.createQuery(hql).setParameter("account", phone).setParameter("idnum", idnumber).list();
			   if (users!=null && users.size()>0) {
				   return 2;
			   }
			   List<Area>areas = mSession.createQuery(hql1).setParameter("areid", areaid).list();
			   if (areas!=null && areas.size()>0) {
				   Area a = areas.get(0);
				   if (a.getPopularity()>=1) {
					   return 3;
				   }
			   }
			   User user = new User(name, phone, idnumber, wechat, identifyicon, authorizedpersonid, "");
			   LoginDao mLoginDao = new LoginDao();
			   com.jm.viewmodel.User upUser = mLoginDao.getUser(authorizedpersonid);
			   Agenttype agenttype = new Agenttype();			   
			   agenttype.setTypeid(Integer.valueOf(level));
			   int  agentLevel = Integer.valueOf(level);
			   int stocks = 0;
			   switch (agentLevel) {
					case 2:
						stocks = 600;
						break;
					case 3:
						stocks = 200;
						break;
					case 4:
						stocks = 48;
						break;
					case 5:
						stocks = 8;
						break;
					default:
						break;
					}
			   user.setAgenttype(agenttype);
			   if(upUser.getArea()!=null){
				   Area area = new Area();			   
//				   area.setAreaid(upUser.getAreaid());
//				   area.setAreaname(upUser.getArea());
				   area.setAreaid(areaid);
				   user.setArea(area);
			   }
			   user.setAccount(phone);
			   user.setCreatetime(new Date(System.currentTimeMillis()));
			   //以身份证后六位作为密码
			   String pwd = "";
			   if(idnumber.length()>6){
				   pwd = idnumber.substring(idnumber.length()-6,idnumber.length());
			   }else
			   {
				   pwd = "123456";
			   }
			   
			   user.setPassword(Utils.EncoderByMd5(pwd));
			   
			   user.setIsauthorize(0);//0 未审核 1 审核通过 2审核失败
			   user.setCreatetime(new Date(System.currentTimeMillis()));
			   mSession.save(user);
			   tx.commit();
			   return 1;
        } catch (RuntimeException e) {
        	 tx.rollback();
            throw e;
        } finally {
			mSession.close();
//			mSessionFactory.close();
		}
	}
	
	@SuppressWarnings("rawtypes")
	public java.util.List<com.jm.viewmodel.User> getAgents(long uid,int isauthorize) {
		java.util.List<com.jm.viewmodel.User>agents= new ArrayList<com.jm.viewmodel.User>();
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();
		Session mSession = mSessionFactory.openSession();
		
		String hql = "from com.jm.entity.User u where authorizedpersonid=:uid and isauthorize=:isauthorize";
		java.util.List<User> users =  mSession.createQuery(hql).setParameter("uid", uid).setParameter("isauthorize", isauthorize).list();
		
		for(User u : users){
				com.jm.viewmodel.User agents1 = new com.jm.viewmodel.User();
				if (u.getAgenttype() != null){ 
					agents1.setAgenttypeid(u.getAgenttype().getTypeid());
					agents1.setAgenttypename(u.getAgenttype().getTypename());
				}
				if(u.getArea()!=null){
					agents1.setArea(u.getArea().getAreaname());
		    	}				
				agents1.setWechat(u.getWechat());
				agents1.setAuthoriSTime(u.getAuthorizestart());
				agents1.setAuthoriETime(u.getAuthorizeend());
				agents1.setAuthorizedpersonid(u.getAuthorizedpersonid());
				agents1.setHeadicon(u.getHeadicon());
				agents1.setUserid(u.getUserid());
				agents1.setNickname(u.getName());
				agents1.setPhone(u.getPhone());
				agents1.setIsAuthorit(String.valueOf(u.getIsauthorize()));
				agents1.setIdnumber(u.getIdnumber());
				agents1.setIdentifyicon(u.getIdentifyicon());
				try {
					agents1.setmkey(Utils.EncoderByMd5(u.getUserid().toString()));
				} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				agents1.setRet("0");
				agents1.setCreateTime(u.getCreatetime());
				agents1.setAuthorizenumber(u.getAuthorizenumber());
				agents1.setAuthorizeimg(u.getAuthorizeimg());
				List<User>downCounts = mSession.createQuery("from com.jm.entity.User u where u.authorizedpersonid=:agentid").setParameter("agentid", agents1.getUserid()).list();
				agents1.setDownagents(String.valueOf(downCounts.size()));
				agents.add(agents1);
		}
		mSession.close();
//		mSessionFactory.close();
		return agents;
		
	}
	
	public synchronized  boolean  authoritUser(int isauthorize,long uid){
		boolean result = false;
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();
		Session mSession = mSessionFactory.openSession();
		Transaction tx = mSession.beginTransaction();
		//系统自动设置授权时间
	    Calendar calendar = Calendar.getInstance();
        Date date = new Date(System.currentTimeMillis());
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, 1);
        date = calendar.getTime();
        int row = 0 ;
        @SuppressWarnings("unchecked")
		List<User>users = mSession.createQuery("from com.jm.entity.User u where u.userid=:uid").setParameter("uid", uid).list();
        if (users!=null && users.size()>0) {
			User user = users.get(0);
			user.setAuthorizestart(new Date(System.currentTimeMillis()));
			user.setAuthorizeend(date);
			user.setIsauthorize(isauthorize);
			user.setAuthorizeimg("/upload/authorit.jpg");
			String authritNumber = "";
			   if(String.valueOf(user.getUserid()).length() ==1){
				    authritNumber = "JMR"+String.format("00000%s", String.valueOf(user.getUserid()));
			   }else if (String.valueOf(user.getUserid()).length() ==2) {
				    authritNumber = "JMR"+String.format("0000%s", String.valueOf(user.getUserid()));
			   }else if (String.valueOf(user.getUserid()).length() ==3) {
				    authritNumber = "JMR"+String.format("000%s", String.valueOf(user.getUserid()));
			   }else if (String.valueOf(user.getUserid()).length() ==4) {
				    authritNumber = "JMR"+String.format("00%s", String.valueOf(user.getUserid()));
			   }else if (String.valueOf(user.getUserid()).length() ==5) {
				    authritNumber = "JMR"+String.format("0%s", String.valueOf(user.getUserid()));
			   }else {
				    authritNumber = "JMR"+String.valueOf(user.getUserid());
			   }
			user.setAuthorizenumber(authritNumber);
			int currentAreaPerson = 0;
			if(user.getArea().getPopularity()!=null){
				currentAreaPerson = user.getArea().getPopularity();
			}
			user.getArea().setPopularity(currentAreaPerson+1);
			mSession.saveOrUpdate(user);
			row = 1;
		}
	   /* Query query = mSession.createQuery("update com.jm.entity.User u set u.isauthorize =:isauthorize,authorizeimg=:authorizeimg where userid=:uid").setParameter("uid", uid).setParameter("isauthorize", isauthorize).setParameter("authorizeimg", "/upload/authorit.jpg");  
	    int row = query.executeUpdate();  */
        mSession.flush();
		tx.commit();
		mSession.close();
//		mSessionFactory.close();
		if(row>0){
			result = true;
		}else{
			result = false;
		}
		return result;
	}
	
	/*public void editUserAddress(long uid){
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();
		Session mSession = mSessionFactory.openSession();
		Transaction tx = mSession.beginTransaction();
		String hql = "from com.jm.entity.User u where u.userid=:uid ";
		List<User>users = mSession.createQuery(hql).setParameter("uid", uid).list();
		int ret =0;
		if(users.size()>0){
			User user = users.get(0);
			Set<Useraddress> mUseraddress = user.getUseraddresses();
		}
		mSession.flush();
		tx.commit();
		mSession.close();
		mSessionFactory.close();
	}
	
	public void addUserAddress(long uid){
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();
		Session mSession = mSessionFactory.openSession();
		Transaction tx = mSession.beginTransaction();
		String hql = "from com.jm.entity.User u where u.userid=:uid ";
		List<User>users = mSession.createQuery(hql).setParameter("uid", uid).list();
		int ret =0;
		if(users.size()>0){
			User user = users.get(0);
			Set<Useraddress> mUseraddress = user.getUseraddresses();
		}
		mSession.flush();
		tx.commit();
		mSession.close();
		mSessionFactory.close();
	}
	
	public void uopdateUserAddress(long uid){
		SessionFactory mSessionFactory = SessionFactoryManager.getInstance();
		Session mSession = mSessionFactory.openSession();
		Transaction tx = mSession.beginTransaction();
		String hql = "from com.jm.entity.User u where u.userid=:uid ";
		List<User>users = mSession.createQuery(hql).setParameter("uid", uid).list();
		int ret =0;
		if(users.size()>0){
			User user = users.get(0);
			Set<Useraddress> mUseraddress = user.getUseraddresses();
		}
		mSession.flush();
		tx.commit();
		mSession.close();
		mSessionFactory.close();
	}
	*/
}
